package day12;

import java.util.concurrent.locks.ReentrantLock;

//a.使用公平锁ReentrantLock实现3个线程交替打印1-100的
//数字，保证每个线程获取锁的机会均等
public class PrintNum {
    ReentrantLock lock=new ReentrantLock(true);
    int num=1;
    public void print(){
        String name=Thread.currentThread().getName();
        lock.lock();
        try {
            //if(num>100) return;
            //Thread.sleep(100);
            System.out.println(name+" "+num++);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        PrintNum pn=new PrintNum();
        for(int i=0;i<3;i++){
            new Thread(()->{
                while(true) {
                    pn.print();
                }
            }).start();
        }
    }
}
